require 'rake_pid/configuration'

module RakePid

  module Core

    def with_pid(task)
      if task.nil? || !task.respond_to?(:name)
        raise TaskMissingError.new("You need to pass the task object to with_pid.")
      end

      pid_file_name = ENV['PIDFILE'] ? ENV['PIDFILE'] : "#{task.name.gsub(':', '-')}.pid"
      pid_file = File.join(Configuration.path, pid_file_name)

      if File.exists?(pid_file)
        if ENV['FORCE'] == 'true'
          File.delete(pid_file) 
        else
          raise FileAlreadyExistError.new("The pid file '#{pid_file}' already exist, delete it and run task again.")
        end
      end

      File.open(pid_file, 'w') { |f| f << Process.pid }
      at_exit do 
        File.delete(pid_file) if File.exists?(pid_file)
      end

      yield
      
      pid_file_name
    end

  end
end
